package top.yqingyu.trans$client.common;

import top.yqingyu.qymsg.MsgHelper;
import top.yqingyu.qymsg.MsgTransfer;
import top.yqingyu.qymsg.QyMsg;
import top.yqingyu.trans$client.main.TransClient;

import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.channels.SocketChannel;
import java.util.concurrent.*;

/**
 * @author YYJ
 * @version 1.0.0
 * @ClassName top.yqingyu.trans$client.common.TransChannel
 * @description
 * @createTime 2023年02月20日 23:56:00
 */
public class TransChannel implements Callable<SocketChannel> {
    private final String host;
    private final int port;
    private String transType;
    private final TransClient client;

    private TransChannel(String host, int port, String transType, TransClient client) {
        this.host = host;
        this.port = port;
        this.transType = transType;
        this.client = client;
    }

    public static SocketChannel getTransChannel(TransClient client, String host, int port, String transType) throws ExecutionException, InterruptedException, TimeoutException, SocketException {

        FutureTask<SocketChannel> socketFutureTask = new FutureTask<>(new TransChannel(host, port, transType, client));
        new Thread(socketFutureTask).start();
        return socketFutureTask.get(3, TimeUnit.SECONDS);
    }

    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    @Override
    public SocketChannel call() throws Exception {
        SocketChannel channel = SocketChannel.open(new InetSocketAddress(host, port));
        QyMsg clone = client.clientConf.AC_MSG.clone();
        clone.putMsg(client.clientConf.AC_STR);

        client.clientConf.msgTransfer.writeQyMsg(channel, clone);
        clone = client.clientConf.NORMAL_MSG.clone();
        clone.putMsg(transType);
        client.clientConf.msgTransfer.writeQyMsg(channel, clone);

        QyMsg msg = client.clientConf.msgTransfer.readQyMsg(channel, 0);

        String s = MsgHelper.gainMsg(msg);
        if ("ok".equals(s))
            return channel;
        return null;
    }
}
